package com.tiger.jms.sample4;

import javax.ejb.EJBException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;

public class PublisherBean implements javax.ejb.SessionBean {
	private javax.ejb.SessionContext sessionContext = null;
	private TopicConnection topicConnection = null;

	public void setSessionContext(javax.ejb.SessionContext sessionContext) {
		this.sessionContext = sessionContext;
	}

	protected void createTopicConnection() {
		try {
			InitialContext ctx = new InitialContext();
			TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("java:comp/env/jms/TopicCF");
			topicConnection = topicConnectionFactory.createTopicConnection();
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	protected void closeTopicConnection() {
		try {
			if (topicConnection != null) {
				topicConnection.close();
				topicConnection = null;
			}
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	public void ejbCreate() {
		createTopicConnection();
	}

	public void publish(String message) {
		try {
			InitialContext ctx = new InitialContext();
			TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			Topic topic = (Topic) ctx.lookup("java:comp/env/jms/sampleTopic");
			TopicPublisher topicPublisher = topicSession.createPublisher(topic);

			topicConnection.start();
			topicPublisher.publish(topicSession.createTextMessage(message));

			topicPublisher.close();
			topicSession.close();
			topicConnection.stop();
		} catch (Exception e) {
			throw new EJBException(e);
		}
	}

	public void ejbPassivate() {
		closeTopicConnection();
	}

	public void ejbActivate() {
		createTopicConnection();
	}

	public void ejbRemove() {
		closeTopicConnection();
	}
}
